<template>
	<view class="body">
		<view class="top-container">
			<uni-list :border="false">
				<uni-list-item :border="false" title="生产订单号" :rightText="header.moBillNo" />
				<uni-list-item :border="false" title="汇报人" :rightText="userName" />
				<uni-list-item :border="false" title="工序号" :rightText="operNo" />
				<!-- <uni-list-item :border="false" title="控制码" :rightText="operpData.control" /> -->
				<uni-list-item :border="false" title="车间" :rightText="operpData.departName" />
				<uni-list-item :border="false" title="铁托号" :rightText="ironNo" />
				<!-- <uni-list-item :border="false" title="物料名称" :rightText="header.materialName" /> -->
				<uni-list-item :border="false" title="件号" :rightText="header.specification" />
				<uni-list-item :border="false" title="工单数量" :rightText="String(header.qty)" />
				<uni-list-item :border="false" title="已汇报数量" :rightText="String(reportSumCount)" />
			</uni-list>
			<view class="panel">
				<view class="panel_content">
					<view class="panel_content_row">
						<view class="panel_content_row_item">
							<view class="panel_content_row_item_title">后缀：</view>
							<view class="panel_content_row_item_value_input">
								<uni-data-select
						
								  v-model="suffix"
								  :localdata="suffixList"
								  placeholder="请选择后缀"
								  :clear="false"
								  custom-style="color: #333; font-size: 14px; border: 1px solid #ccc; background-color: #fff; border-radius: 4px; padding: 6rpx 12rpx; width: 100%;"
								/>
							</view>
			
						</view>
					</view>
				</view>
			</view>

			<view class="panel">
				<view class="panel_content">
					<view class="panel_content_row">
						<view class="panel_content_row_item">
							<view class="panel_content_row_item_title">批号：</view>
							<view class="panel_content_row_item_value_input">
								<input v-model="flot" type="text" placeholder="请输入批号"  />
							</view>

						</view>
					</view>
				</view>
			</view>

			<view class="panel">
				<view class="panel_content">
					<view class="panel_content_row">
						<view class="panel_content_row_item">
							<view class="panel_content_row_item_title">合格数量：</view>
							<view class="panel_content_row_item_value_input">
								<input v-model="quaQty" type="number" placeholder="请输入合格数量" @input="handleQuality()" />
							</view>

						</view>
					</view>
				</view>
			</view>

			<view class="panel">
				<view class="panel_content">
					<view class="panel_content_row">
						<view class="panel_content_row_item">
							<view class="panel_content_row_item_title">工废数量：</view>
							<view class="panel_content_row_item_value_input">
								<input v-model="processFailQty" type="number" placeholder="请输入工废数量"
									@input="handleFailQty()" />
							</view>
						</view>

					</view>
				</view>
			</view>


			<view class="panel">
				<view class="panel_content">
					<view class="panel_content_row">
						<view class="panel_content_row_item">
							<view class="panel_content_row_item_title">料废数量：</view>
							<view class="panel_content_row_item_value_input">
								<input v-model="materialFailQty" type="number" placeholder="请输入料废数量"
									@input="handleMaterialFailQty()" />
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="panel">
				<view class="panel_content">
					<view class="panel_content_row">
						<view class="panel_content_row_item">
							<view class="panel_content_row_item_title">完工数量：</view>
							<view class="panel_content_row_item_value_input">
								<input v-model="endQty" type="number" placeholder="完工数量" class="editable-input"
									disabled />
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="panel">
				<view class="panel_content">
					<view class="panel_content_row">
						<view class="panel_content_row_item">
							<view class="panel_content_row_item_title">工时(分钟)：</view>
							<view class="panel_content_row_item_value_input">
								<input v-model="workTime" type="number" placeholder="请输入工时(分钟)"
									class="editable-input" />
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="panel">
				<view class="panel_content">
					<view class="panel_content_row">
						<view class="panel_content_row_item">
							<view class="panel_content_row_item_title">入库时间：</view>
							<view class="panel_content_row_item_value_input">
								<uni-datetime-picker type="datetime" v-model="inStockTime" @change="onInStockTimeChange"
									placeholder="请选择入库时间">
								</uni-datetime-picker>
							</view>
						</view>
					</view>
				</view>
			</view>

			<view class="panel">
				<!--  底部按钮  -->
				<view class="footerPanelgx">
					<view class="footerPanelgx_body">
						<!-- <button @click="handlePrint()" class="footerBtngx scan" type="primary"><i
								class="iconfont icon-saomiao btn_icon"></i>打印托盘
						</button> -->
						<!-- <button  @click="pickScan" class="footerBtngx scan" type="primary"><i
								class="iconfont icon-saomiao btn_icon"></i>扫码
						</button> -->
						<button @click="saveReport" class="footerBtngx save" :disabled="buttonStatus"><i
								class="iconfont icon-duihao btn_icon"></i>保存工序汇报
						</button>

					</view>
				</view>
			</view>
		</view>
	<!-- 扫描托盘 -->
	<tray-popup ref="trayPopupRef" @success="trayScanningScuess"></tray-popup>
	</view>

</template>

<script>
	import uniTransition from 'uni_modules/uni-transition/components/uni-transition/uni-transition.vue';
	import uniEmptyInfo from "../../vBase/components/uni-empty-info/uni-empty-info.vue"
	import trayPopup from '../../components/popup/trayPopup.vue'
	import {
		getTrayPlan,
		getProPlanisDetail,
		getOptrptisDetail,
		saveReport,
		verifyIronTray,
		createTrayPda,
		selectSuffix
	} from '@/utils/api.js'
	import {
		printContect,
		printQRCode,
		printVerticalLabel,
		printData,
		safePrint,
		printTextAndQRCode
	} from '@/utils/print.js'

	export default {
		components: {
			uniEmptyInfo,
			trayPopup
		},
		data() {
			return {
				billNo: '',
				suffix:'',//后缀
				quaQty: '', //合格数量
				workTime: '', //工时
				processFailQty: '', //工废数量
				materialFailQty: '', //料废数量
				endQty: '', //完工数量
				operNo: '', //工序计划单号
				inStockTime: this.getTodayDateTime(),
				loading: true,
				header: {},
				trayData: {},
				departName: '',
				trayNo: '',
				flot:'',//批号
				buttonStatus:false,
				reportSumCount: 0,
				userName: '', //登录的用户
				operpData: {}, //工序计划详情
				ironNo:'',//铁托编号
				suffixList:[
				],
			}
		},
		methods: {
			getSuffix(){
				selectSuffix({}).then(res =>{
					this.suffixList = res.data.data.dataList
				})
			},
			//扫码成功后返回
			trayScanningScuess(e){
				let _this = this;
				//校验铁托是否存在，是否被占用
				verifyIronTray({billNo : e}).then(res =>{
					if(res.data.data == true){
						this.ironNo = e
						uni.showToast({
							title: "扫码成功",
							icon: "success"
						})
					}
				})
			},
			//扫码获取铁托信息
			pickScan(){
				this.$refs.trayPopupRef.open()
			
			},
			onInStockTimeChange(val) {
				// 有些端返回时间戳或 ISO 格式，这里统一转成 yyyy-MM-dd HH:mm:ss
				if (typeof val === 'string') {
					this.inStockTime = val.length > 19 ? val.slice(0, 19).replace('T', ' ') : val
				} else {
					this.inStockTime = this.formatDateTime(new Date(val))
				}
			},
			formatDateTime(date) {
				const y = date.getFullYear();
				const m = String(date.getMonth() + 1).padStart(2, '0');
				const d = String(date.getDate()).padStart(2, '0');
				const h = String(date.getHours()).padStart(2, '0');
				const min = String(date.getMinutes()).padStart(2, '0');
				const s = String(date.getSeconds()).padStart(2, '0');
				return `${y}-${m}-${d} ${h}:${min}:${s}`;
			},
			getTodayDateTime() {
				return this.formatDateTime(new Date());
			},
			createTrayPda() {
				let _this = this;
				let map = {
					itemnumber: this.header.materialNo,
					fqty: this.quaQty,
					operNo: this.header.billNo,
					flot: this.flot,
					suffix: this.suffix,
					ironNo:this.ironNo,
					inStockTime: this.inStockTime //入库时间
				}
				createTrayPda(map).then(res => {
					if (res.data.status === 200) {
						this.trayNo = res.data.msg
						saveReport({
							operpData: _this.operpData,
							header: _this.header,
							workTime: _this.workTime,
							processFailQty: _this.processFailQty,
							materialFailQty: _this.materialFailQty,
							endQty: _this.endQty,
							quaQty: _this.quaQty,
							trayData: _this.trayData,
							inStockTime: _this.inStockTime,
							trayNo: _this.trayNo,
							flot: _this.flot
											
						}).then(result => {
							if (result.data.data) {
								//保存成功后弹出是否需要打印
								uni.showModal({
									title: '保存成功',
									content: '是否打印托盘信息',
									success(res) {
										if (res.confirm) {
											let values = {
												'件号': _this.header.specification,
												'数量': _this.quaQty,
												'批号': _this.flot,
												'后缀': _this.suffix
											};
											safePrint() //校验打印机是否连接
											printVerticalLabel(values, _this.trayNo)
											_this.buttonStatus = false
										}
									}
								})
							} 
						}).catch(err => {
							// console.log(err)
							_this.buttonStatus = false
						})
						
					}
				})
			},
			//打印
			handlePrint() {
				//托盘数量为合格数量
				if (!this.quaQty || this.quaQty === "0") {
					uni.showModal({
						title: '提示',
						content: '请输入合格数量才能打印',
						showCancel: false
					})
					return;
				}
				//打印之前需要调用后端接口新增托盘
				// this.createTrayPda()
				let values = {
					'件号': this.header.specification,
					'数量': this.quaQty,
					'批号': this.flot,
					'后缀': this.suffix
				};
				safePrint() //校验打印机是否连接
				printVerticalLabel(values, this.trayData.fbillno)

			},

			//调整完工数量
			changeEndqty() {
				// this.quaQty =  Number(this.trayCount) - Number(this.processFailQty) - Number(this.materialFailQty)
				this.endQty = Number(this.quaQty) + Number(this.processFailQty) + Number(this.materialFailQty)
			},

			//填写料废数量
			handleMaterialFailQty() {
				const v = this.materialFailQty
				const zero = "(/^\D*(\d*(?:\.\d{0,2})?).*$/g,'$1')"
				let final = 0
				if (!v) {
					final = 0
				} else {
					final = v.toString().replace(zero, (v) => {
						return 0
					})

					if (final.split('')[0] * 1 === 0) {
						final = final.slice(1) - 0 || 0
					}
				}
				this.$nextTick(() => {
					this.materialFailQty = final.toString() || '0'
					this.changeEndqty()
				})


			},
			//填写工费数量
			handleFailQty() {
				const v = this.processFailQty
				const zero = "(/^\D*(\d*(?:\.\d{0,2})?).*$/g,'$1')"
				let final = 0
				if (!v) {
					final = 0
				} else {
					final = v.toString().replace(zero, (v) => {
						return 0
					})

					if (final.split('')[0] * 1 === 0) {
						final = final.slice(1) - 0 || 0
					}
				}
				this.$nextTick(() => {
					this.processFailQty = final.toString() || '0'
					this.changeEndqty()
				})


			},
			//填写合格数量
			handleQuality() {
				const v = this.quaQty
				const zero = "(/^\D*(\d*(?:\.\d{0,2})?).*$/g,'$1')"
				let final = 0
				if (!v) {
					final = 0
				} else {
					final = v.toString().replace(zero, (v) => {
						return 0
					})

					if (final.split('')[0] * 1 === 0) {
						final = final.slice(1) - 0 || 0
					}
				}
				this.$nextTick(() => {
					this.quaQty = final.toString() || '0'
					this.changeEndqty()
				})


			},
			saveReport() {
				//机加车间和包装车间的需要扫描托盘
				// if (!this.ironNo) {
				// 	uni.showModal({
				// 		title: '提示',
				// 		content: '请扫描铁托汇报',
				// 		showCancel: false
				// 	})
				// 	return;
				
				// }
				if (this.endQty == 0) {
					uni.showModal({
						title: '提示',
						content: '请确认完工数量',
						showCancel: false
					})
					return;
				}


				let _this = this
				uni.showModal({
					title: '提示',
					content: '确认保存汇报单',
					success(res) {
						if (res.confirm) {
							_this.buttonStatus = true
							//先生成托盘码
							_this.createTrayPda()
							
						}
					}
				})
			},
			// 获取详情数据
			initData() {
				getProPlanisDetail({
					billNo: this.billNo,
					operNo: this.operNo
				}).then(res => {
					if (res.statusCode === 200) {
						this.header = res.data.data.data;
						this.reportSumCount = res.data.data.reportCount;
						const detail = res.data.data.dataList;
						detail.forEach(item => {
							if (item.operNo == this.operNo) {
								this.operpData = item
								this.departName = item.departName
							}
						})
					}
				}).catch(err => {
					// 错误处理保持不变...
				});
				this.userName = uni.getStorageSync('userName')
			},
		},
		watch: {
			// userInfo() {
			// 	console.log(this.userInfo())
			// }
		},
		mounted() {
			let self = this;
			uni.$on('update', function(data) {
				self.initData()
			})
		},
		onLoad(options) {
			try {
				this.billNo = options.billNo
				this.operNo = options.operNo
				this.initData()
				this.getSuffix()
			} catch (e) {
				uni.showToast({
					title: "加载失败",
					icon: "none"
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import "../../static/css/common";

	/* 调整列表项左右文字大小 */
	::v-deep .uni-list-item__content-title {
		font-size: 22px !important;
		/* 左侧标题字体大小 */
		padding-left: 5px;
	}

	::v-deep .uni-list-item__extra-text {
		font-size: 22px !important;
		/* 右侧内容字体大小 */
		padding-right: 5px;
		color: #333;
	}

	/* 调整行间距 */
	::v-deep .uni-list-item__container {
		padding: 3px 0 !important;
		/* 减小上下内边距 */
		min-height: 10px !important;
		/* 减小最小高度 */
	}

	/* 调整标题样式 */
	.panel_content_row_item_title {
		font-size: 20px !important;
		/* 调大字体 */
		color: #000000 !important;
		/* 纯黑字体 */
		flex-shrink: 0;
		/* 防止压缩 */
	}

	/* 调整输入框容器 */
	.panel_content_row_item_value_input {
		flex: 1;
		/* 占据剩余空间 */
		margin-left: 10px;
		/* 增加左右间距 */
	}

	/* 调整输入框本身 */
	.panel_content_row_item_value_input input {
		height: 45px !important;
		/* 调高输入框 */
		font-size: 30px !important;
		/* 同步调大输入文字 */
		// padding: 1px 12px !important;
		border: 1px solid #ddd;
		/* 增加边框更清晰 */
		border-radius: 4px;
	}

	/* 调整行间距 */
	.panel_content_row {
		padding: 1px 0 !important;
		/* 减小上下内边距 */
	}

	// 底部按钮
	.footerPanelgx {
		height: 90px;

		.footerPanelgx_body {
			display: flex;
			justify-content: center;
			gap: 20px;
			padding: 0 20px;

			.footerBtngx {
				height: 55px;
				margin: 0 5px;
				display: flex;
				line-height: 1;
				font-size: 16px;
				border-radius: 4px;
				align-items: center;
				justify-content: center;
				box-shadow: 0 0 5px rgba(201, 201, 201, 0.5);
				color: #fff;

				&.save {
					background-color: $uni-color-success;
					width: 150px;
					flex-shrink: 0;
				}

				&.scan {
					background: $primary;
					width: 150px;
					flex-shrink: 0;
				}
			}

			.btn_icon {
				margin-right: 8px;
			}
		}
	}
</style>